package cn.edu.nju.software.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.util.Properties;

public class PreferencesOperator {
	
	public String[] getProperties(String[] keys) {
		Properties props = new Properties();
		try {
			InputStream inputStream = new BufferedInputStream(new FileInputStream(getFilePath()));
			props.load(inputStream);
			inputStream.close();
			int size = keys.length;
			String[] values = new String[size];
			for (int i=0; i<size; i++) {
				values[i] = props.getProperty(keys[i]);
			}
			return values;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	public void saveProperties(String[] keys, String[] values) {
		Properties props = new Properties();
		try {
			InputStream inputStream = new BufferedInputStream(new FileInputStream(getFilePath()));
			props.load(inputStream);
			inputStream.close();
			int size = keys.length;
			for (int i=0; i<size; i++) {
				props.setProperty(keys[i], values[i]);
			}
			OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(getFilePath()));
			props.store(outputStream, "");
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private String getFilePath() {
		try {
			String classPath = getClass().getResource("/").toURI().getPath();
			return classPath + Constants.PREFERENCES_FILE_NAME;
		} catch (URISyntaxException e) {
			e.printStackTrace();
			return null;
		}
	}
}
